<template>
  <el-dialog v-model="visible" :title="title" @close="cancel" width="80%">
    <el-form ref="authorityFrom" :model="dataForm" :rules="dataRules" label-width="100px">
      <el-form-item label="栏目权限" prop="name">
        <el-select v-model="dataForm.columnPermissions" style="width: 100%" @change="changeColumn">
          <el-option v-if="rowDate.level == 1" label="一级管理员" :value="1" />
          <el-option v-if="rowDate.level != 1" label="二级管理员" :value="2" />
          <el-option label="内容编辑人员" :value="3" />
        </el-select>
      </el-form-item>
      <table style="width: 100%">
        <tr>
          <td>选择用户</td>
          <td v-if="dataForm.columnPermissions == 3" style="padding-left: 50px">栏目按钮权限</td>
          <td v-else style="padding-left: 50px">全部栏目按钮权限</td>
          <td v-if="dataForm.columnPermissions == 3" style="padding-left: 50px">内容按钮权限</td>
          <td v-else style="padding-left: 50px">全部内容按钮权限</td>
        </tr>
        <tr v-for="item in userList">
          <td>
            <el-checkbox @change="handleChange" v-model="item.userId" :label="item.username" :true-value="item.id" :false-value="undefined" />
          </td>

          <td  style="padding-left: 50px">
            <ma-dict-checkbox v-model="item.buttonPermissions" dict-type="column_button_permissions" style="width: 100%"></ma-dict-checkbox>
          </td>
          <td  style="padding-left: 50px">
            <ma-dict-checkbox v-model="item.contentPermission" dict-type="content_permission" style="width: 100%"></ma-dict-checkbox>
          </td>
        </tr>
      </table>
    </el-form>
    <template #footer>
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="submit()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, defineProps, nextTick } from 'vue'
import { ElMessage } from 'element-plus/es'
import { getAllUser, authoritySave } from '@/api/allApi'

const emit = defineEmits(['resetList'])
const props = defineProps<{ selectedList: ContentItem[] }>()

const visible = ref(false)
const title = ref('分配权限')
const dialogType = ref('add')
const authorityFrom = ref()
const dataForm = reactive({
  columnPermissions: null
})
const dataRules = reactive({})
const rowDate = reactive({})
const userList = ref([])
const allList = ref([])

const init = (type: string, row: any) => {
  visible.value = true
  dialogType.value = type
  console.log(row, 'row')
  Object.assign(rowDate, row) //浅拷贝，将row赋值给rowDate，用以前直接=赋值的形式会报错
  getAllUser().then(res => {
    userList.value = res.data.list
    if (type == 'add') {
      title.value = '分配权限'
    } else {
      title.value = '编辑权限'
      nextTick(() => {
        if (rowDate.level == 1) {
          changeColumn(1)
        } else {
          changeColumn(2)
        }
      })
    }
  })
  let data = []
  data.push(rowDate.id)
  if (rowDate.children) {
    var childId = getAllChildIds(rowDate.children)
    data.push(...childId)

  }
  console.log(data)
  allList.value = data
}

// 递归函数，获取所有子集的 id
function getAllChildIds(nodes) {
  let ids = []
  nodes.forEach(node => {
    // 添加当前节点的 id
    if (node.id) {
      ids.push(node.id)
    }
    // 如果当前节点有子节点，则递归处理子节点
    if (node.children && node.children.length > 0) {
      ids = ids.concat(getAllChildIds(node.children)) // 合并子节点的 id
    }
  })
  return ids
}
const handleChange = val => {
  //处理
  if(dataForm.columnPermissions != 3){
    userList.value.forEach(j => {
      j.buttonPermissions = ''
      j.contentPermission=''
      if(j.userId){
        j.buttonPermissions = '1,2,3,4,5,6,7'
        j.contentPermission='1,2,3,4,5,6'
      }
    })
  }
}

const changeColumn = val => {
  if (dialogType.value == 'edit') {
    selectClear()
    for (var i = 0; i < rowDate.agCategoryPermissions.length; i++) {
      var ss = rowDate.agCategoryPermissions[i]
      userList.value.forEach(j => {
        console.log(j, 'j')
        if (ss.columnPermissions == val) {
          // 确保 j 存在
          console.log(j, 'watchj', ss)
          if (j.id === ss.userId) {
            j.userId = ss.userId
            j.buttonPermissions = ss.buttonPermissions ? ss.buttonPermissions:''
            j.contentPermission = ss.contentPermission ? ss.contentPermission:''
            j.categoryId = ss.categoryId
            if (val != 3) {
              j.buttonPermissions = '1,2,3,4,5,6,7'
              j.contentPermission='1,2,3,4,5,6'
            }
          }
        }
      })
    }
    dataForm.columnPermissions = val
  }
}
const submit = () => {
  authorityFrom.value.validate((valid: any) => {
    if (valid) {
      let params = []
      if (dialogType.value == 'add') {
        props.selectedList.forEach(i => {
          userList.value.forEach(j => {
            if (j.userId) {
              params.push({
                categoryId: i.id,
                userId: j.userId,
                columnPermissions: dataForm.columnPermissions,
                buttonPermissions: j.buttonPermissions,
                contentPermission:j.contentPermission
              })
            }
          })
        })
      } else {
        allList.value.forEach(i => {
          userList.value.forEach(j => {
            if (dataForm.columnPermissions != 3) {
              j.buttonPermissions = '1,2,3,4,5,6,7'
              j.contentPermission='1,2,3,4,5,6'
            }
            if (j.userId) {
              params.push({
                categoryId: i,
                userId: j.userId,
                columnPermissions: dataForm.columnPermissions,
                buttonPermissions: j.buttonPermissions,
                contentPermission:j.contentPermission
              })
            }
          })
        })
        if (params.length == 0) {
          //没有数据说明是删除操作
          allList.value.forEach(i => {
            params.push({
              categoryId: i,
              userId: '',
              columnPermissions: dataForm.columnPermissions,
              buttonPermissions: '',
              contentPermission:'',
            })
          })
        }
      }
      authoritySave(params).then(res => {
        ElMessage.success('操作成功')
        cancel()
        emit('resetList')
      })
    }
  })
}
const selectClear = () => {
  userList.value.forEach(i => {
    i.userId = ''
    i.buttonPermissions = ''
    i.contentPermission=''
    i.categoryId = ''
  })
}
const cancel = () => {
  visible.value = false
  dataForm.columnPermissions = null
  selectClear()
}

defineExpose({
  init
})
</script>
<style lang="scss" scoped>
</style>
